<?php
namespace app\logic;
require_once "../common/corelib/wxPay/lib/WxPay.Api.php";
require_once '../common/corelib/wxPay/lib/WxPay.Notify.php';
require_once '../common/corelib/wxPay/example/WxPay.JsApiPay.php';
use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\common\PayUtil;
use app\models\Chapter;
use app\models\Course;
use app\models\Order;
use Beanstalk\Client;
use WxPayUnifiedOrder;
use WxPayApi;
use JsApiPay;
use yii;

class OrderLogic
{
    public function createCancelNo(){
        return mt_rand(10000000,99999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function createOrderNo(){
        return date('Ymd').mt_rand(100000,999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function saveOrder($open_id,$order_type,$course_id=0,$chapter_id=0){
        $order = new Order();
        $order_no = $this->createOrderNo();
        $order2 = Order::findOne(['order_no'=>$order_no]);
        while($order2){
            $order_no = $this->createOrderNo();
            $order2 = Order::findOne(['order_no'=>$order_no]);
        }
        $order->order_no = $order_no;
        $userLogic = new UserLogic();
        $user = $userLogic->findByOpenid($open_id);
        $order->user_id = $user['user_id'];
        if($order_type){
            $course = Course::find()->where(['course_id'=>$course_id])->asArray()->one();
            $order->order_amount = $course['course_price'];
            $order->course_id = $course_id;
            $body = $course['course_name'];
        }else{
            $chapter = Chapter::find()->where(['chapter_id'=>$chapter_id])->asArray()->one();
            $order->order_amount = $chapter['chapter_price'];
            $order->course_id = $chapter['course_id'];
            $order->chapter_id = $chapter_id;
            $body = $chapter['chapter_name'];
        }
        $order->order_type = $order_type;
        $order->order_time = date('Y-m-d H:i:s');
        //正式改回来
        //$order->order_status = 1;
        //正式改回来
        $orderresult = $order->save();
        if($orderresult){
            $result = $this->_wxPay($body,$order_no,$order->order_amount,$open_id);
            if($result['return_code']=='SUCCESS'){
                $tools = new JsApiPay();
                $jsApiParameters = $tools->GetJsApiParameters($result);
                $jsApiParameters_arr = json_decode($jsApiParameters,true);
                $jsApiParameters_arr['order_no'] = $order_no;
                return $jsApiParameters_arr;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    private function _wxPay($body,$order_no,$price,$openid){

        //require_once "WxPay.JsApiPay.php";
        //require_once 'log.php';
        $input = new WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetAttach("none");
        $input->SetOut_trade_no($order_no);
        $input->SetTotal_fee($price*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("none");
        $input->SetNotify_url(Yii::$app->params['wxPay']['notify_url']);
        $input->SetTrade_type("JSAPI");
//        $userLogic = new UserLogic();
//        $user = $userLogic->getUser($user_id);
        //$input->SetOpenid($user->open_id);
        $input->SetOpenid($openid);
        $order = WxPayApi::unifiedOrder($input);
        return $order;
    }

    /*public function paySuccess($order_no,$pay_time,$pay_no,$thirdPartyCode,&$order_id){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $order = Order::findOne(['order_no'=>$order_no]);
        if($order->order_status==0){
            $order->order_status = 1;
            $time = date('Y-m-d H:i:s');
            $order->pay_type = $thirdPartyCode;
            $order->pay_time = date('Y-m-d H:i:s',strtotime($pay_time));
            $order->pay_no = $pay_no;
            $order->update_time = $time;
            $result1 = $order->save();
            $order_id = $order->order_id;
            $skutemp = OrderGoods::find()->where(['order_id'=>$order_id])->asArray()->all();
            $goods_sale_volume = [];
            $result5 = true;
            foreach($skutemp AS $key=>$value){
                if(isset($goods_sale_volume[$value['goods_id']])){
                    $goods_sale_volume[$value['goods_id']] += $value['buy_num'];
                }else{
                    $goods_sale_volume[$value['goods_id']] = $value['buy_num'];
                }
                $sku[$key]['skuId'] = $value['yx_sku_id'];
                $sku[$key]['productName'] = $value['goods_name'];
                $sku[$key]['saleCount'] = $value['buy_num'];
                $sku[$key]['originPrice'] = $value['channel_price'];
                $sku[$key]['subtotalAmount'] = $value['channel_price']*$value['buy_num'];
                $goodsSku = GoodsSku::findOne($value['sku_id']);
                $goodsSku->sku_sales_volume += $value['buy_num'];
                $result5 &= $goodsSku->save();
            }
            $result3 = true;
            foreach($goods_sale_volume AS $kk=>$vv){
                $goods = Goods::findOne($kk);
                $goods->sales_volume += $vv;
                $result3 &= $goods->save();
            }

            $order = [
                'orderId'=>$order_no,
                'submitTime'=>$order->order_time,
                'payTime'=>$order->pay_time,
                'receiverName'=>$order->consignee,
                'receiverPhone'=>$order->consignee_phone,
                'receiverProvinceName'=>$order->consignee_province,
                'receiverCityName'=>$order->consignee_city,
                'receiverDistrictName'=>$order->consignee_district,
                'receiverAddressDetail'=>$order->consignee_address,
                'realPrice'=>$order->channel_amount,
                'expFee'=>$order->shipping_fee,
                'payMethod'=>$thirdPartyCode,                                //此处
                'orderSkus'=>$sku
            ];
            $result = HttpCurl::post("yanxuan.order.paid.create",['order'=>json_encode($order)]);
            $result = json_decode($result,true);
            $result2 = true;
            $result4 = true;
            foreach($result['orderPackages'] AS $key=>$value){
                $package = new Package();
                $package->yx_package_id = $value['packageId'];
                $package->order_id = $order_id;
                $package->package_status = 2;
                $result2 &= $package->save();
                $skus = $value['orderSkus'];
                foreach($skus AS $kk=>$vv){
                    $og = OrderGoods::findOne(['order_id'=>$order_id,'yx_sku_id'=>$vv['skuId']]);
                    $og->package_id = $package->package_id;
                    $result4 &= $og->save();
                }
            }
            if($result1 && $result2 && $result3 && $result4 && $result5){
                $transaction->commit();
                return true;
            }else{
                $transaction->rollBack();
                return false;
            }
        }else{
            return false;
        }

    }*/

    public function haveBuy($open_id,$course_id,$chapter_id=0){
        if($chapter_id){
            return Order::find()
                ->from('{{%order}} o')
                ->leftJoin('{{%user}} u','u.user_id=o.user_id')
                ->where(['o.order_type'=>0,'u.open_id'=>$open_id,'o.chapter_id'=>$chapter_id,'o.order_status'=>1])
                ->asArray()
                ->one();
        }else{
            return Order::find()
                ->from('{{%order}} o')
                ->leftJoin('{{%user}} u','u.user_id=o.user_id')
                ->where(['o.order_type'=>1,'u.open_id'=>$open_id,'o.course_id'=>$course_id,'o.order_status'=>1])
                ->asArray()
                ->one();
        }

    }





}
